﻿using AutoMapper;
using B.S.GridManage.Api.Read.Application.Command.PhisicalGrid;
using B.S.GridManage.Domain.Entities;
using B.S.GridManage.ErrorCode;
using B.S.GridManage.Infrastructure.Interface;
using MediatR;
using System.Transactions;
using Yitter.IdGenerator;

namespace B.S.GridManage.Api.Read.Application.Handler.PhisicalGrid
{
    public class CopyPhsicalGridHandler : IRequestHandler<CopyPhsicalGridCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<PhysicallGridModel> gridRepo;
        private readonly IMapper mapper;

        public CopyPhsicalGridHandler(IBaseRepository<PhysicallGridModel> gridRepo,IMapper mapper)
        {
            this.gridRepo = gridRepo;
            this.mapper = mapper;
        }
        /// <summary>
        /// 批量添加&复制物理网格
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(CopyPhsicalGridCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();

            List< PhysicallGridModel > models = new List<PhysicallGridModel> ();
            //循环前端传入的请求数组,转换为实体列表
            foreach (var dto in request.dtos)
            {
                var model = mapper.Map<PhysicallGridModel>(dto);
                model.Id = YitIdHelper.NextId();
                models.Add(model);
            }

            int r = 0;

            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    r = await gridRepo.AddRangeAsync(models);//把models 批量添加到数据库
                    tran.Complete();//提交事务
                }
                catch (Exception)
                {
                    //记录异常日志
                }
            }
            res.Code = ApiEnum.Success;
            res.Data = r;
            res.Msg = "批量操作成功!";
            return res;
        }
    }
}
